package com.momoauth.common.tps.aliyun.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AliyunSmsUtil {

    /**
     * 发送短信
     * @param accessKeyID accessKeyID
     * @param accessKeySecret accessKeySecret
     * @param phoneNumbers  接收短信的手机号码
     * @param signName      短信签名名称
     * @param templateCode  短信模板CODE
     * @param templateParam 短信模板变量对应的实际值
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static SendSmsResponseBody sendSMS(
            String accessKeyID,
            String accessKeySecret,
            String phoneNumbers,
            String signName,
            String templateCode,
            String templateParam
    ) throws ExecutionException, InterruptedException {
        // 设置身份验证信息
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyID)
                .accessKeySecret(accessKeySecret)
                .build());
        // 配置客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
        // API请求参数
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signName)
                .templateCode(templateCode)
                .phoneNumbers(phoneNumbers)
                .templateParam(templateParam)
                .build();
        // 异步获取API请求的返回值
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 输出打印Body的信息
        System.out.println(new Gson().toJson(response.get().getBody()));
        // 关闭客户端
        client.close();
        return response.get().getBody();
    }
}
